#include "palette/WWClassicVGAPalette.h"
#include <palette/Palette.h>
#include <common/Logger.h>
#include <vector>
#include <fstream>

using namespace std;

shared_ptr<IPalette> WWClassicVGAPaletteReader::ReadFormFile(const string &file)
{
    vector<Color> vc;
    vc.reserve(256);
    ifstream is;
    is.open(file, ios::in | ios::binary);
    uint8_t temp[3];
    for(size_t i = 0; i < 256; i++)
    {
        is.read((char*)&temp, 3);
        uint8_t r = temp[0] << 2;
        uint8_t g = temp[1] << 2;
        uint8_t b = temp[2] << 2;
        vc.emplace_back(Color(r, g, b, 255));
    }
    return make_shared<Palette>(vc);
}

void WWClassicVGAPaletteWriter::WriteToFile(const string &file, const IPalette &palette)
{
    Logger::Warning("WW Classic VGA Palette will lose color accuracy(24-bit RGBA to 18-bit RGB).");
    if (palette.GetLength() > 256)
        Logger::Warning("WW Classic VGA Palette will only write 256 Colors to the file.");
    ofstream os;
    os.open(file, ios::out | ios::trunc | ios::binary);
    uint8_t temp[3];
    for(size_t i = 0; i < 256; i++)
    {
        auto c = palette.GetColor(i);
        temp[0] = c.r >> 2;
        temp[1] = c.g >> 2;
        temp[2] = c.b >> 2;
        os.write((char*)temp, 3);
    }
}
